package com.linghui.videoplus.ipai.api.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.linghui.videoplus.ipai.api.WSError;

public class HttpClientAPI {

	/**
	 * http do get
	 * @param httpAddress
	 * @param requestProperty
	 * @return
	 * @throws WSError
	 */
	public static String doGet2Api(String httpAddress,String[][] requestProperty) throws WSError {
		HttpURLConnection connection = null;
		try {
			URL url = new URL(httpAddress);
			connection = (HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(60000);
			connection.setReadTimeout(60000);
			connection.setDoOutput(true);
			connection.setChunkedStreamingMode(0);
			if (requestProperty != null) {
				for (String[] rp : requestProperty) {
					connection.addRequestProperty(rp[0], rp[1]);
				}
			}
			return convertStreamToString(connection.getInputStream());
		} catch (MalformedURLException e) {
			WSError wsError = new WSError();
			wsError.setMessage(e.getLocalizedMessage());
			throw wsError;
		} catch (IOException e) {
			WSError wsError = new WSError();
			wsError.setMessage(e.getLocalizedMessage());
			throw wsError;
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
	}

	/**
	 * 类型转换
	 * @param is
	 * @return
	 */
	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
}
